package com.itheima.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.rowset.spi.SyncResolver;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: homechen
 * Date: 2024-04-26
 * Time: 23:27
 */
@Configuration
public class DeadConfig {
    // 创建死信队列
    @Bean
    public DirectExchange deadExchange() {
        return new DirectExchange("deadExchange.direct", true, false); // 是否持久化  + 自动删除
    }

    // 创建死信队列
    @Bean
    public Queue deadQueue() {
        return new Queue("deadQueue.queue", true, false, false);   // exclusive 是否独有 ？ 队列只有一个吗
    }

    // 死信队列跟死信交换机绑定
    @Bean
    public Binding deadRoutingBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with("deadRouting");
    }

    // 转发到死信队列 参数
    private Map<String, Object> deadQueueArgs() {
        Map<String, Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", "deadExchange.direct");
        map.put("x-dead-letter-routing-key", "deadRouting");
        return map;
    }

    // 正常交换机
    @Bean
    public DirectExchange normalExchange() {
        return new DirectExchange("normalExchange.direct", true, false);
    }

    // 正常队列  - 长度限制
    @Bean
    public Queue normalQueue() {
        Map<String, Object> args = deadQueueArgs();
        args.put("x-max-length", 5);
        return new Queue("normalQueue.queue", true, false, false, args);
    }

    // 时间受限制
    @Bean
    public Queue ttlQueue() {
        Map<String, Object> args = deadQueueArgs();
        args.put("x-message-ttl", 60 * 1000);
        return new Queue("ttlQueue.queue", true, false, false, args);
    }

    @Bean
    public Binding normalBinding() {
        return BindingBuilder.bind(normalQueue()).to(normalExchange()).with("normalRouting");
    }

    @Bean
    public Binding ttlBinding() {
        return BindingBuilder.bind(ttlQueue()).to(normalExchange()).with("ttlRouting");
    }
}
